<template>
  <div>
    <div class="welcome-container">
      <div class="welcome-content">
        <!-- 用户信息卡片 -->
        <el-card shadow="hover" class="user-info">
          <div class="user-info-container">
            <div class="user-info-wrapper">
              <el-avatar
                :class="{ 'avatar-spin': showEasterEgg }"
                :size="80"
                :src="
                  userInfo.avatar ||
                  'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
                "
                @click="handleAvatarClick"
              />
              <div class="user-details">
                <h3 class="welcome-title">欢迎回来，{{ userInfo.nickname }}</h3>
                <div class="user-meta">
                  <div class="meta-item">
                    <i class="el-icon-office-building" />
                    <span class="label">所属部门：</span>
                    <span class="value">{{ userInfo.section }}</span>
                  </div>
                  <div class="meta-item">
                    <i class="el-icon-phone" />
                    <span class="label">联系电话：</span>
                    <span class="value">{{ userInfo.phone }}</span>
                  </div>
                  <div class="meta-item">
                    <i class="el-icon-user" />
                    <span class="label">学工号：</span>
                    <span class="value">{{ userInfo.henauNumber }}</span>
                  </div>
                  <div class="meta-item">
                    <i class="el-icon-info" />
                    <span class="label">身份状态：</span>
                    <span class="value">{{
                      getIdentityStatus(userInfo.identity_status)
                    }}</span>
                  </div>
                  <div class="meta-item">
                    <i class="el-icon-user" />
                    <span class="label">角色：</span>
                    <span class="value">
                      <el-tag
                        v-for="role in userInfo.roles"
                        :key="role"
                        class="role-tag"
                        :type="getRoleTagType(role)"
                      >
                        {{ role }}
                      </el-tag>
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 中间卡片区域 -->
        <div class="middle-container flex flex-wrap gap-4 mb-4">
          <!-- 快捷操作 -->
          <el-card shadow="hover" class="flex-1 min-w-[300px]">
            <template #header>
              <div class="flex items-center justify-between">
                <span class="font-bold">快捷操作</span>
              </div>
            </template>
            <div class="quick-actions grid grid-cols-2 gap-4">
              <el-card
                v-for="action in quickActions"
                :key="action.title"
                :type="action.type"
                class="h-[80px] flex flex-col items-center justify-center cursor-pointer hover:scale-105 transition-transform"
                @click="action.handler"
              >
                <el-icon :size="24" class="mb-2">
                  <component :is="action.icon" />
                </el-icon>
                <span>{{ action.title }}</span>
              </el-card>
            </div>
          </el-card>

          <!-- 系统信息 -->
          <el-card shadow="hover" class="flex-1 min-w-[300px]">
            <template #header>
              <div class="flex items-center justify-between">
                <span class="font-bold">系统信息</span>
              </div>
            </template>
            <el-descriptions :column="1" border>
              <el-descriptions-item
                v-for="item in systemInfo"
                :key="item.label"
                :label="item.label"
              >
                {{ item.value }}
              </el-descriptions-item>
            </el-descriptions>
          </el-card>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import {
  User,
  Setting,
  List,
  Document,
  Key,
  Monitor,
  Operation,
  Refresh,
  Coordinate,
  Guide,
  Finished,
  UserFilled
} from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import { useUserStoreHook } from "@/store/modules/user";
import { storageLocal } from "@pureadmin/utils";
import { userKey } from "@/utils/auth";
import { ElMessage } from "element-plus";

const router = useRouter();
const userStore = useUserStoreHook();
const userInfo = ref({
  nickname: userStore.nickname,
  avatar: userStore.avatar,
  lastLogin: "",
  section: "",
  phone: "",
  henauNumber: userStore.username,
  roles: [],
  identity_status: 0,
  created_at: "",
  updated_at: ""
});

// 统计数据
const statisticsData = ref([
  {
    title: "总人员数",
    value: "1000",
    icon: User,
    iconClass: "text-blue-500"
  },
  {
    title: "系统角色",
    value: "1000",
    icon: Monitor,
    iconClass: "text-green-500"
  },
  {
    title: "系统权限",
    value: "1000",
    icon: Key,
    iconClass: "text-yellow-500"
  },
  {
    title: "操作日志",
    value: "1000",
    icon: Operation,
    iconClass: "text-purple-500"
  }
]);

// 快捷操作
const quickActions = ref([
  {
    title: "人员管理",
    icon: UserFilled,
    type: "success",
    handler: () => {
      router.push("/user");
    }
  },
  {
    title: "使用文档",
    icon: Document,
    type: "warning",
    handler: () => {
      router.push("/document");
    }
  }
]);

// 系统信息
const systemInfo = ref([
  { label: "系统名称", value: "河南农业大学人员组织管理系统" },
  { label: "系统版本", value: "v1.0.0" },
  { label: "上线时间", value: "2025-02-12" },
  { label: "系统时间", value: new Date().toLocaleString() }
]);

const avatarClickCount = ref(0);
const showEasterEgg = ref(false);

onMounted(() => {
  initUserInfo();
  // 同步更新store中的信息
  const localUserInfo = storageLocal().getItem(userKey);
  if (localUserInfo) {
    userStore.SET_USERNAME(localUserInfo.username);
    userStore.SET_NICKNAME(localUserInfo.nickname);
    userStore.SET_AVATAR(localUserInfo.avatar);
    userStore.SET_ROLES(localUserInfo.roles);
    userStore.SET_PERMS(localUserInfo.permissions);
  }
});

// 初始化用户信息
const initUserInfo = () => {
  const localUserInfo = storageLocal().getItem(userKey) || {};
  if (localUserInfo) {
    userInfo.value = {
      nickname: localUserInfo.nickname || "",
      avatar: localUserInfo.avatar || "",
      lastLogin: localUserInfo.last_login || "暂无登录记录",
      section: localUserInfo.section || "暂无部门信息",
      phone: localUserInfo.phone || "暂无联系方式",
      henauNumber: localUserInfo.username || "",
      roles: localUserInfo.roles || [],
      identity_status: localUserInfo.identity_status || 0,
      created_at: localUserInfo.created_at || "",
      updated_at: localUserInfo.updated_at || ""
    };
  }
};

const getIdentityStatus = status => {
  const statusMap = {
    0: "本科生",
    1: "研究生",
    2: "在校教职工",
    3: "在校后勤/外聘人员",
    4: "已毕业校友",
    5: "中国现代农业联合研究生院学生"
  };
  return statusMap[status] || "未知状态";
};

const getRoleTagType = role => {
  const typeMap = {
    admin: "danger",
    teacher: "warning",
    student: "success",
    staff: "info"
  };
  return typeMap[role.toLowerCase()] || "primary";
};

const handleAvatarClick = () => {
  avatarClickCount.value++;
  if (avatarClickCount.value === 10) {
    showEasterEgg.value = true;
    ElMessage({
      message: "🎉 哇！你发现了隐藏彩蛋！",
      type: "success",
      duration: 3000
    });
    setTimeout(() => {
      showEasterEgg.value = false;
      avatarClickCount.value = 0;
    }, 3000);
  }
};

const formatNumber = num => {
  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
};

const formatLargeNumber = num => {
  if (num >= 100000000) {
    return (num / 100000000).toFixed(2) + "亿";
  } else if (num >= 10000) {
    return (num / 10000).toFixed(2) + "万";
  }
  return formatNumber(num);
};

// 获取统计数据
const fetchStatisticsData = async () => {
  try {
    const res = await getStatistics();
    if (res.status === "success" && res.data) {
      const { records, system } = res.data;

      // 计算总用户数
      const totalUsers =
        records.data_undergraduate +
        records.data_postgraduate +
        records.data_staff +
        records.data_external_staff +
        records.data_ugscma_postgraduate;

      // 更新统计数据
      statisticsData.value[0].value = formatLargeNumber(totalUsers);
      statisticsData.value[1].value = formatLargeNumber(system.table_role);
      statisticsData.value[2].value = formatLargeNumber(
        system.table_permission
      );
      statisticsData.value[3].value = formatLargeNumber(
        system.table_admin_operation_log
      );
    }
  } catch (error) {
    console.error("获取统计数据失败:", error);
  }
};
</script>

<style lang="scss" scoped>
@keyframes spin {
  0% {
    transform: rotate(0deg) scale(1);
  }

  50% {
    transform: rotate(180deg) scale(1.5);
  }

  100% {
    transform: rotate(360deg) scale(1);
  }
}

@keyframes float {
  0% {
    transform: translateY(0);
  }

  50% {
    transform: translateY(-10px);
  }

  100% {
    transform: translateY(0);
  }
}

@keyframes gradient-bg {
  0% {
    background-position: 0% 50%;
  }

  50% {
    background-position: 100% 50%;
  }

  100% {
    background-position: 0% 50%;
  }
}

@media (width <= 768px) {
  .user-info {
    flex-direction: column;
    text-align: center;
  }

  .statistics-container {
    grid-template-columns: 1fr;
  }
}

.welcome-container {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 60%;
  max-height: 90%;
  background-size: 200% 200%;
  animation: gradient-bg 15s ease infinite;
}

.welcome-content {
  width: 90%;
  max-width: 1200px;
  padding: 40px;
}

.user-info {
  margin-bottom: 40px;
  overflow: hidden;
  border: none;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgb(0 0 0 / 8%);
  transition: all 0.3s ease;

  &:hover {
    box-shadow: 0 8px 25px rgb(0 0 0 / 12%);
    transform: translateY(-8px);
  }

  .user-info-container {
    padding: 20px;
  }

  .user-info-wrapper {
    display: flex;
    gap: 24px;
    align-items: flex-start;

    @media (width <= 640px) {
      flex-direction: column;
      align-items: center;
      text-align: center;
    }
  }

  .el-avatar {
    flex-shrink: 0;
    border: 4px solid #fff;
    box-shadow: 0 4px 15px rgb(0 0 0 / 10%);
    transition: all 0.3s ease;

    &:hover {
      box-shadow: 0 6px 20px rgb(0 0 0 / 15%);
      transform: scale(1.1);
    }
  }

  .user-details {
    flex: 1;
    min-width: 0; // 防止flex子项溢出

    .welcome-title {
      margin: 0 0 20px;
      overflow: hidden;
      font-size: 1.8rem;
      font-weight: bold;
      text-overflow: ellipsis;
      white-space: nowrap;
      background: linear-gradient(120deg, #1890ff, #36cfc9);
      background-clip: text;
      -webkit-text-fill-color: transparent;
    }

    .user-meta {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
      gap: 16px;

      @media (width <= 640px) {
        grid-template-columns: 1fr;
      }

      .meta-item {
        display: flex;
        gap: 8px;
        align-items: center;
        padding: 8px;
        border-radius: 8px;
        transition: all 0.3s ease;

        &:hover {
          background-color: rgb(24 144 255 / 10%);
          transform: translateX(5px);
        }

        i {
          font-size: 1.1em;
          color: #1890ff;
        }

        .label {
          white-space: nowrap;
        }

        .value {
          flex: 1;
          min-width: 0;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .role-tag {
          margin: 0 4px;
          font-size: 0.9rem;
          font-weight: 500;

          &:first-child {
            margin-left: 0;
          }
        }
      }
    }
  }
}

.statistics-container {
  .statistics-card {
    overflow: hidden;
    border: none;
    border-radius: 12px;
    box-shadow: 0 4px 20px rgb(0 0 0 / 8%);
    transition: all 0.3s ease;

    &:hover {
      box-shadow: 0 8px 25px rgb(0 0 0 / 12%);
      transform: translateY(-8px);

      .el-icon {
        animation: float 2s ease-in-out infinite;
      }
    }

    .text-gray-500 {
      font-size: 1rem;
      font-weight: 500;
      color: #666;
    }

    .text-2xl {
      font-size: 2rem;
      font-weight: 600;
      background: linear-gradient(120deg, #1890ff, #36cfc9);
      background-clip: text;
      -webkit-text-fill-color: transparent;
    }

    .el-icon {
      opacity: 0.9;
      transition: all 0.3s ease;
    }
  }
}

.middle-container {
  min-height: 400px;

  .el-card {
    border: none;
    border-radius: 12px;
    box-shadow: 0 4px 20px rgb(0 0 0 / 8%);
    transition: all 0.3s ease;

    &:hover {
      box-shadow: 0 8px 25px rgb(0 0 0 / 12%);
      transform: translateY(-8px);
    }

    .el-card__header {
      border-bottom: 1px solid rgb(0 0 0 / 5%);

      .font-bold {
        font-size: 1.1rem;
        color: #1890ff;
      }
    }
  }
}

.quick-actions {
  .el-card {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 80px;
    border: 1px solid rgb(24 144 255 / 10%);
    transition: all 0.3s ease;

    .el-icon {
      top: 5px;
      margin-right: 8px;
      color: #666;
      transition: all 0.3s ease;
    }

    span {
      font-weight: 500;
      color: #666;
      transition: all 0.3s ease;
    }

    &:hover {
      border-color: #1890ff;
      box-shadow: 0 8px 25px rgb(24 144 255 / 15%);

      .el-icon {
        color: #1890ff;
        transform: scale(1.2) rotate(10deg);
      }

      span {
        color: #1890ff;
      }
    }
  }
}

:deep(.el-timeline-item__content) {
  padding: 8px 12px;
  font-size: 0.95rem;
  color: #666;
  border-radius: 6px;
  transition: all 0.3s ease;

  &:hover {
    color: #1890ff;
    background: rgb(24 144 255 / 10%);
    transform: translateX(8px);
  }
}

:deep(.el-descriptions) {
  .el-descriptions-item__label {
    width: 120px;
    font-weight: 500;
    color: #666;
    background: rgb(248 249 250 / 80%);
  }

  .el-descriptions-item__content {
    padding: 12px 16px;
    color: #333;
    transition: all 0.3s ease;

    &:hover {
      color: #1890ff;
      background: rgb(24 144 255 / 5%);
      transform: translateX(8px);
    }
  }
}

.avatar-spin {
  cursor: pointer;
  animation: spin 1s ease-in-out infinite;
}
</style>
